import React, { useState, useRef, useEffect } from 'react';
import { Input, Tag, AutoComplete, Badge, Tooltip } from 'antd';
import debounce from 'lodash.debounce';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { DeviceListItem } from '../data.d';
import TagCommonComponent from '../../System/components/TagCommonComponent';
import { deviceList } from '../service';
import { planDetail } from '../../Plan/service';
import { parseInt } from 'lodash';
import styles from '../index.less';

interface DeviceComponentProps {
  planCode: string; // 【添加设备分组弹出框】传值计划空 【计划审核弹出框--设备列表】传值计划code
  topOrgId: number;
  type: string; //undefined:新建 ，edit:编辑，detail：详情
  data: [];//用于设备分组详情，存放设备列表数据
  deviceIds: [];
  setDeviceIds: (deviceIds: []) => void;
}

const { Search } = Input;

const DeviceComponent: React.FC<DeviceComponentProps> = (props) => {
  const actionRef = useRef<ActionType>();
  const [orgId, setOrgId] = useState<number>(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [tagsValue, setTagsValue] = useState<string>("");

  const { planCode, topOrgId, type, data, deviceIds, setDeviceIds } = props;

  useEffect(() => {//初始化设备列表选中状态
    setSelectedRowKeys(deviceIds);
  }, [deviceIds]);


  useEffect(() => {
    setOrgId(topOrgId);
    setTagsValue(undefined);
  }, [topOrgId]);

  const requestObj = new Object();
  if (type == "detail") {
    if (data.length > 0) {
      requestObj["data"] = data;
      for (let i in requestObj.data) {
        requestObj.data[i]["key"] = parseInt(i);
        requestObj.data[i]["resolution"] = requestObj.data[i].width + "x" + requestObj.data[i].height;
      }
    } else {
      requestObj["data"] = [];
    }
    actionRef.current?.reload();
  }

  const columns: ProColumns<DeviceListItem>[] = [
    {
      title: '设备名称',
      dataIndex: 'name',
      width: 150,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="设备名称"
              onSearch={debounce(value => { form.submit() }, 500)}
              onChange={debounce(value => { form.submit() }, 500)}
              style={{ width: 150 }}
            />
          );
        }
        return defaultRender(_);
      },
      valueType: 'text'
    },
    {
      title: 'MAC地址',
      dataIndex: 'mac',
      width: 120,
      hideInSearch: true,
      valueType: 'text',
    },
    {
      title: '分辨率',
      dataIndex: 'resolution',
      width: 100,
      formItemProps: {
        rules: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                const n = (value.split('x')).length - 1;
                if (n == 1) {
                  callback();
                } else {
                  callback("分辨率只能包含一个x，介于长和宽中间");
                }
              } else {
                callback();
              }
            },
          }
        ],
      },
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <AutoComplete
              style={{ width: 150 }}
              options={[{ label: "全部分辨率", value: '' }, { value: '1920x1080' }, { value: '1080x1920' }]}
              onSelect={(value) => { form.submit() }}
            >
              <Input.Search
                allowClear
                placeholder="分辨率"
                onSearch={(value) => { form.submit() }}
              />
            </AutoComplete>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '所属机构',
      dataIndex: 'orgName',
      width: 100,
      hideInSearch: true,
      hideInTable: type == "detail" ? true : false,
      valueType: 'text',
    },
    {
      title: '所属分组',
      dataIndex: 'groups',
      valueType: 'text',
      hideInSearch: true,
      width: 120,
      render: groups => (
        <>
          {groups?.map((group, index) => {
            return (
              <Tag color="blue" key={index} title={group} style={{ marginBottom: 5, display: 'inline-block', overflow: 'hidden', whiteSpace: 'pre', textOverflow: 'ellipsis', maxWidth: 110 }}>
                {group}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '当前计划',
      dataIndex: 'nowPlanName',
      valueType: 'text',
      ellipsis: true,
      width: 110,
      hideInSearch: true,
      render: (_, record) => (
        record.nowPlanName ?
          <Tooltip title={record.nowPlanName}>
            <label style={{ minWidth: 50, width: 110, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', display: 'block' }}>{record.nowPlanName}</label>
          </Tooltip> : (
            record.defaultPlanName ?
              <Badge count="默认计划" size="small" style={{ background: '#1890ff', color: '#fff' }}>
                <Tooltip title={record.name}>
                  <label style={{ minWidth: 50, maxWidth: 110, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', display: 'block' }}>{record.defaultPlanName}</label>
                </Tooltip>
              </Badge>
              : "--")
      )
    },
    {
      title: '在线状态',
      dataIndex: 'onlineStatus',
      width: 90,
      hideInSearch: true,
      valueType: 'text',
      valueEnum: {
        ONLINE: { text: '在线', status: 'Success' },
        OFFLINE: { text: '离线', status: 'Warning' },
      },
    },
    {
      title: '标签',
      dataIndex: 'tagIds',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <TagCommonComponent
              value={tagsValue}
              form={form}
              topOrgId={topOrgId > 0 ? topOrgId : JSON.parse(localStorage.getItem("user")).topOrgId}
              selectChange={(values) => {
                form.setFieldsValue({ "tagIds": values.toString() });
                setTagsValue(values.toString());
                form.submit();
              }}>
            </TagCommonComponent>
          );
        }
        return defaultRender(_);
      },
      hideInTable: true,
      valueType: 'text',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      valueType: 'text',
      width: 150,
      hideInSearch: true,
      render: tags => (
        <>
          {tags?.map((tag, index) => {
            return (
              <Tag color="blue" key={index} title={type == "plan" ? tag : tag.name} style={{ marginBottom: 5, display: 'inline-block', overflow: 'hidden', whiteSpace: 'pre', textOverflow: 'ellipsis', maxWidth: 130 }}>
                {type == "plan" ? tag : tag.name}
              </Tag>

            );
          })}
        </>
      ),
    },
  ];

  return (
    <ProTable<DeviceListItem>
      className={styles.DeviceComponent}
      // size="small"
      options={false}
      actionRef={actionRef}
      rowKey="key"
      search={(type != "detail" && type != "plan") ? {
        labelWidth: 70,
        span: 6,
        collapsed: false,
        collapseRender: () => false //隐藏收起按钮
      } : false}
      pagination={{ showQuickJumper: true, defaultPageSize: 10 }}
      params={{ "orgId": orgId > 0 ? orgId : null, "tagIds": tagsValue }}
      request={(params, sorter, filter) => //planCode：计划审核--设备详情
        type != "detail" ? (planCode ? planDetail(planCode) : deviceList({ ...params, sorter, filter })) : requestObj
      }
      columns={columns}
      rowSelection={(type != "detail" && type != "plan") ? {
        selectedRowKeys: selectedRowKeys,
        onSelect: (record, selected) => {
          if (selected) {//选中
            setSelectedRowKeys([...selectedRowKeys, record.key]);
            setDeviceIds([...selectedRowKeys, record.key]);
          } else {//取消选中
            const newKeys = selectedRowKeys.concat();
            const index = newKeys.indexOf(record.key);
            newKeys.splice(index, 1);
            setSelectedRowKeys(newKeys);
            setDeviceIds(newKeys);
          }
        },
        onSelectAll: (selected, selectedRows1, changeRows) => {
          if (selected) {//全选
            const keys = [];
            for (let i = 0; i < changeRows.length; i++) {
              const record = changeRows[i];
              keys.push(record.key);
            }
            setSelectedRowKeys([...selectedRowKeys, ...keys]);
            setDeviceIds([...selectedRowKeys, ...keys]);
          } else {//取消全选
            const newSelectedRowKeys = selectedRowKeys.concat();
            for (let i = 0; i < changeRows.length; i++) {
              const record = changeRows[i];
              for (let j = 0; j < newSelectedRowKeys.length; j++) {
                if (record.key == newSelectedRowKeys[j]) {
                  newSelectedRowKeys.splice(j, 1);
                }
              }
            }
            setSelectedRowKeys(newSelectedRowKeys);
            setDeviceIds(newSelectedRowKeys);
          }
        }
      } : false}
      tableAlertOptionRender={() => {
        return (<a onClick={() => {
          setSelectedRowKeys([]);
          setDeviceIds([]);
          actionRef.current?.clearSelected?.();
        }}>清空</a>)
      }}
      scroll={{ y: 240 }}
    />
  );
};

export default DeviceComponent;
